<template>
  <div class="user-list">
    <el-card class="box-card">
      <div slot="header">
        <div class="action">
          <div>
            <span>手机号&emsp;</span>
            <el-input
              placeholder="用户手机号"
              v-model="conditionObj.phone"
              clearable
            >
            </el-input>
          </div>
          <div>
            <span>注册时间&emsp;</span>
            <el-date-picker
              v-model="dataRange"
              @change="dateChange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </div>
          <el-button @click="resetCondition">重置</el-button>
          <el-button :loading="isLoading" @click="searchUser" type="primary"
            >查询</el-button
          >
        </div>
      </div>
      <el-table :data="userData" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="150">
        </el-table-column>
        <el-table-column prop="name" label="头像" width="100">
          <template slot-scope="scope">
            <img
              width="30px"
              :src="
                scope.row.portrait ||
                  'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
              "
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名"> </el-table-column>
        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column prop="createTime" label="注册时间">
          <!-- 用户状态操作（服务端没有开放权限，只能演示） -->
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <div
              v-if="scope.row.status !== 'ENABLE'"
              style="width: 20px;height: 20px; border-radius: 50%; background-color: #ff6b6b"
            ></div>
            <div
              v-else
              style="width: 20px;height: 20px; border-radius: 50%;background-color: #51cf66"
            ></div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button @click="changeUserStatus(scope.row)" type="text">{{
              scope.row.status === 'ENABLE' ? '禁用' : '启用'
            }}</el-button>
            <el-button @click="allocRole(scope.row)" type="text"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配用户对话框结构 -->
    <el-dialog title="分配用户" :visible.sync="dialogVisible" width="30%">
      <span>分配角色：</span>
      <el-select v-model="seletedRole" multiple placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAllocRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserPages, forbidUser, enableUser } from '@/service/user'
import { getAllRole, allocateUserRoles, getUserRole } from '@/service/role'
export default {
  name: 'user',
  data () {
    return {
      isLoading: false,
      userData: [],
      //   角色列表
      options: [],
      // 用户新增或编辑弹窗是否显示
      dialogVisible: false,
      dataRange: [],
      seletedRole: [],
      currentUser: {},
      conditionObj: {
        currentPage: 1,
        pageSize: 200,
        phone: '',
        startCreateTime: '',
        endCreateTime: ''
      }
    }
  },
  created () {
    this.loadUser()
    this.loadAllRole()
  },
  methods: {
    // 打开用户新增或编辑对话框
    openDialog () {
      this.isEdit = false
      this.dialogFormVisible = true
    },
    // 日期选择变化
    dateChange (date) {
      this.conditionObj.startCreateTime = date[0]
      this.conditionObj.endCreateTime = date[1]
    },
    // 分配菜单
    async allocRole (row) {
      const { data } = await getUserRole(row.id)
      if (data.code === '000000') {
        this.seletedRole = data.data.map(m => m.id)
        this.currentUser = row
        this.dialogVisible = true
      }
    },
    // 分配菜单
    async confirmAllocRole () {
      const { data } = await allocateUserRoles({
        userId: this.currentUser.id,
        roleIdList: this.seletedRole
      })
      if (data.code === '000000') {
        this.$message.success('用户角色权限分配成功')
        this.dialogVisible = false
      }
    },
    // 改变用户状态
    async changeUserStatus (row) {
      if (row.status === 'ENABLE') {
        const { data: data1 } = await enableUser({
          userId: row.id
        })
        if (data1.code == 200) {
          this.loadAllRole()
        }
      } else {
        const { data } = await forbidUser({
          userId: row.id
        })
        if (data.code === '000000') {
          this.loadAllRole()
        }
      }
    },
    // 搜索用户
    searchUser () {
      this.isLoading = true
      this.loadUser()
    },
    // 重置搜索条件
    resetCondition () {
      this.conditionObj.phone = ''
      this.conditionObj.startCreateTime = ''
      this.conditionObj.endCreateTime = ''
      this.dataRange = []
      this.loadUser()
    },
    // 加载所有角色
    async loadAllRole () {
      const { data } = await getAllRole()
      if (data.code === '000000') {
        this.options = data.data
      }
    },
    async loadUser () {
      const { data } = await getUserPages(this.conditionObj)
      if (data.code === '000000') {
        this.isLoading = false
        this.userData = data.data.records
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.mt30 {
  margin-top: 30px;
}

.box-card {
  text-align: left;
  .action {
    display: flex;
    align-items: center;
    > div {
      display: flex;
      align-items: center;
      margin-left: 20px;
    }
    .el-button {
      margin-left: 16px;
    }
  }
  // .search {
  //   margin-top: 30px;
  //   > span {
  //     width: 100px;
  //   }
  //   .el-input {
  //     width: 300px;
  //   }
  //   display: flex;
  //   align-items: center;
  // }
}
</style>
